/**
 *  Server.js
 *  @description it supports a htpp server and websock server.
 */

const controllers = require('./controllers'),
  routes = require('./routes').routes,
  ws = require('nodejs-websocket'),
  proc = require('child_process'),
  http = require('http'),
  url = require('url'),
  fs = require('fs');

/**
 *  HTTP Server
 */
http.createServer(function controllersr(req, res) {
  var pathname = url.parse(req.url).pathname;
  req.setEncoding('utf8');
  // Controllers are called
  if (routes[pathname]) {
    if (controllers.isAuth(req)) {
      routes[pathname](req, res);
    } else {
      controllers.login(req, res);
    }
  } else {
    var file = './ui' + pathname;
    // Like access to a static file server
    fs.exists(file, function(ex) {
      if (ex) {
        fs.readFile(file, [], function(err, data) {
          res.end(data);
        });
      } else {
        console.log('No request controllers found for ' + pathname);
        res.writeHead(404, {
          'Content-Type': 'text/plain'
        });
        res.write('404 Not found');
        res.end();
      }
    });
  }
}).listen(3000);

console.log('HTTP Server running at http://0.0.0.0:3000/');

/**
 *  WebSocket Server
 */
var server = ws.createServer(function(conn) {

  var log = proc.spawn('tail', ['-f', '/var/log/syslog']); // Read from local log file.

  log.stdout.on('data', function(data) {
    conn.sendText(JSON.stringify(data.toString().split('\n')));
  });

  conn.on('close', function(code, reason) {
    log.kill('SIGHUP');
  });
}).listen(3001);

console.log('WebSocket Server running at http://0.0.0.0:3001/');
